package ying.response;/**
 * ClassName: RespDownload01
 * Package: ying.response
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/10/3 22:12
 * @Version 1.0
 */

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/resp/download01")
public class RespDownload01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取fileName参数
        String fileName = request.getParameter("fileName");
        //2.设置MIME和下载响应头 Content-Disposition: attachment;filename=文件名
        String mimeType = getServletContext().getMimeType(fileName);
        response.setHeader("Content-Type", mimeType);
        response.setHeader("Content-Disposition","attachment;filename=" + fileName);
        //3.将指定的文件的字节写给浏览器
        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        InputStream is = getServletContext().getResourceAsStream("/download/" + fileName);
        BufferedInputStream bis = new BufferedInputStream(is);

        int b;
        while((b = bis.read()) != -1) {
            bos.write(b);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
